import asyncio
import logging
from fileinput import filename

from fastapi import FastAPI
from redbird.repos import CSVFileRepo, MemoryRepo
from rocketry import Rocketry
from rocketry.log import MinimalRecord, LogRecord

from afast_core.core_plugins.loguru import logger
from afast_core.core_plugins.pluginbase import IBasePlugin as BasePlugin
from pydantic import BaseSettings as Settings

from afast_core.core_plugins.scheduler.rocketry.enums import RunModel

from multiprocessing import Value


class RocketrySchedulerPluginClient(BasePlugin):
    # 设置插件默认的参数信息
    name = 'RocketryScheduler插件'

    class SchedulerConfig(Settings):
        run_model = RunModel.in_app
        # execution-----------任务胡执行
        # main：在主进程和线程中执行（默认）
        # process：在单独进程中执行
        # thread：在单独线程中执行
        # async：异步执行
        execution: str = 'async'
        # 只是只允许https读取
        # 内置日志格式有：
        # rocketry.log.MinimalRecord: 最简略的日志
        # rocketry.log.LogRecord: 经典的日志元素
        # rocketry.log.TaskLogRecord: 类似 LogRecord，同时包含开始、结束、运行次数

    def setup(self, app: FastAPI, name: str = None, *args, **kwargs):
        """插件初始化"""

        self._schedule_app = Rocketry(logger_repo=MemoryRepo(model=LogRecord),
                                      config={"task_execution": self.settings.execution})

        # 注册不同的实例对象
        app.rocke_schedule_plugin_client = self
        app.state.rocke_schedule = self._schedule_app

        # 如果运行的模式在App内直接的启动，那么直接的启动就好
        if self.settings.run_model == RunModel.in_app:
            @app.on_event("startup")
            async def start_scheduler() -> None:
                #  rocketry_server
                asyncio.create_task(self._schedule_app.serve())
                logger.info(f"Rocketry startup event start", event_name='Rocketry 定时任务模块')

            @app.on_event("shutdown")
            async def stop_scheduler() -> None:
                logger.info(f"Rocketry startup event stop", event_name='Rocketry 定时任务模块')

        # @core_app.on_event("startup")
        # def startup_event():
        #     print("启动应用程序啦")
        #     asyncio.create_task(core_app.schedule.serve())
        #     # items["foo"] = {"name": "Fighters"}

    @property
    def task(self):
        return self._schedule_app.task

# @core_app.infirmary_tasks(every('10 seconds', based="finish"))
# async def do_permanently():
#     "This runs for really long time"
#     await asyncio.sleep(600000)
#
# @core_app.infirmary_tasks(every('2 seconds', based="finish"))
# async def do_short():
#     "This runs for short time"
#     await asyncio.sleep(1)
#
# @core_app.infirmary_tasks(every('20 seconds', based="finish"))
# async def do_long():
#     "This runs for long time"
#     await asyncio.sleep(60)
#
# @core_app.infirmary_tasks(every('10 seconds', based="finish"))
# async def do_fail():
#     "This fails constantly"
#     await asyncio.sleep(10)
#     # raise RuntimeError("Whoops!")
#
# if __name__ == "__main__":
#     # Run only Rocketry
#     core_app.run()
